package com.smarth.zhizulian.http.observable;

import android.util.Log;

import com.smarth.zhizulian.bean.BaseEntity;
import com.smarth.zhizulian.http.exception.ApiException;
import com.smarth.zhizulian.utils.KumaLog;
import com.smarth.zhizulian.utils.QiNiuUtils;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;

import org.json.JSONObject;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;

/**
 * Created by 18865 on 2017/12/28.
 */

public class QiNiuObservable implements ObservableSource<String> {
    private String mData;
    private String mKey;
    private String mToken;

    public QiNiuObservable(String data, String key, String token) {
        this.mData = data;
        this.mKey = key;
        this.mToken = token;
    }

    @Override
    public void subscribe(final Observer<? super String> observer) {
        QiNiuUtils.getUploadManager().put(mData, mKey, mToken,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        //res包含hash、key等信息，具体字段取决于上传策略的设置
                        if (info.isOK()) {
                            KumaLog.qiniu("Upload Success");
                            observer.onNext(key);
                            observer.onComplete();
                        } else {
                            KumaLog.qiniu("Upload Fail");
                            //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                            BaseEntity be = new BaseEntity();
                            be.setCode("-93");
                            be.setMessage("图片服务器上传失败");
                            observer.onError(new ApiException(be));
                        }
                        KumaLog.qiniu(key + ",\r\n " + info + ",\r\n " + res);
                    }
                }, null);
    }
}
